package org.bluweb.g4wicket.feed;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.wicket.markup.html.IHeaderResponse;
import org.bluweb.g4wicket.G4WicketComponent;

@SuppressWarnings("serial")
public class DynamicFeedControl extends G4WicketComponent {

	private Map<String,String> feeds = new HashMap<String, String>();
	private Map<String,String> options = new HashMap<String, String>();
	
	public DynamicFeedControl( String id ) {
		super( id );
	}
	
	@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead( response );
		response.renderCSSReference( "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css" );
		response.renderJavascriptReference( "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js" );
	}

	public DynamicFeedControl addFeed( String title, String rssUrl ) {
		this.feeds.put( title, rssUrl );
		return this;
	}
	
	public DynamicFeedControl setStacked( boolean stacked ) {
		return this.setOption( "stacked", String.valueOf( stacked ) );
	}

	public DynamicFeedControl setTitle( String title ) {
		return this.setOption( "title", "'" + title + "'" );
	}
	
	public DynamicFeedControl setNumberOfResult( int number ) {
		return this.setOption( "numResults", String.valueOf( number ) );
	}
	
	private DynamicFeedControl setOption( String name, String value ) {
		this.options.put( name, value );
		return this;
	}
	
	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();
		
		Map<String,Object> parameters = new HashMap<String,Object>();

		StringBuilder builder = new StringBuilder();
		for( String title : this.feeds.keySet() ) {
			if( builder.length() > 0 ) {
				builder.append( ',' );
			}
			builder.append( "{title:'" ).append( title );
			builder.append( "',url:'" ).append( feeds.get( title ) ).append( "'}" );
		}

		parameters.put( "feeds", builder.toString() );
		
		builder = new StringBuilder();
		for( String name : options.keySet() ) {
			if( builder.length() > 0 ) {
				builder.append( ',' );
			}
			builder.append( name ).append( ":" );
			builder.append( options.get( name ) );
		}
		
		parameters.put( "options", builder.toString() );
		
		this.setJavaScriptTemplate( "DynamicFeedControl.js", true, parameters );
	}	
}
